<?php
namespace Admin\Controller;
use Admin\Controller;
Vendor('Qiniu.autoload');
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
/**
 * 分类管理
 */
class EntController extends BaseController
{

    /**
     * 添加数据
     * @return [type] $mode $key
     */
    public function addAdmin()
    {
        if(IS_POST){
            $newname = trim($_POST['newname']);//服务器名称
            if(!empty($newname)){//添加新服
                $time = time();
                if(empty($newname)){
                    $this->success("新服名称不能为空！", U('Ent/addAdmin'));exit();
                }
                $newserver[] = array('newname'=>$newname,'createtime'=>$time);
                $add_new_server =M('new_server')->addAll($newserver);
                if($add_new_server){
                    $this->success("新服名称上传成功！", U('Ent/addAdmin'));exit();
                }else{
                    $this->success("新服名称上传失败！请重新上传！", U('Ent/addAdmin'));exit();
                }
            }
            $journalism['createtime'] = time();
            $journalism['status']     = trim($_POST['num']);
            $journalism['title']      = trim($_POST['title']);
            $journalism['content']    = trim($_POST['ueditor']);
            if(!empty($journalism['title']) && !empty($journalism['status']) && !empty($journalism['content'])){//添加新闻

                $addjournalism = M('journalism')->add($journalism);
                if($addjournalism){
                    $data = array('result' => 1, 'msg' => "数据添加成功！");
                    echo json_encode($data);die;
                }else{
                    $data = array('result' => 0, 'msg' => "数据添加失败！");
                    echo json_encode($data);die;
                }

            }else{
                 $data = array('result' => 0, 'msg' => "提交数据不能有空！");
                 echo json_encode($data);die;
            }
        }
            $this->display();   
    }

    /**
     *@ uplode 图片上传
     * 添加图鉴
     */
    public function uplode(){

        if(IS_POST){
            $type = I('image');
            $count = I('num');//星级宠物图

            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     314572800 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Public/upload/'; // 设置附件上传根目录  
            $upload->savePath  =     ''; // 设置附件上传（子）目录
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = '@.ORG.Image';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            $upload->replace           = true;
            //删除原图
            $upload->thumbRemoveOrigin  = true;
            // 上传文件
            $info=array();
           
            $info1   =  $upload->upload();
            // echo '<pre>';
            // print_r($info1);die;

            foreach ($info1 as $key=>$value)
            {
                $imgs=$_SERVER["DOCUMENT_ROOT"].'/hcxy/server/Public/upload/'.$value['savepath'].$value['savename'];
                $imgsname = $value['savename'];
                $path = $this->Test($imgs,$imgsname);
                $url_img[$key]     = 'http://image.jswl.cc/'.$path['key'];//七牛云 图片路径

            }
            $tt  = count($url_img);

            $where = I('listRows');// id
            $list = I('list');

            if(!empty($list) && !empty($where)){

                if($list=='list'){
                    if($tt !== 2 && $tt !== 0){
                         $this->success("图片上传错误1，请重新上传", U('Ent/index'));exit();
                    }
                    if(!empty($url_img)){
                        $save['img'] = $url_img[0];
                        $save['big_img'] = $url_img[1];
                    }
                    $save['status'] = I('cont');
                    $listsave = M('list_image')->where('id='.$where)->save($save);
                }
                if($list=='ctivity'){
                    if($tt !== 1 && $tt !== 0){
                         $this->success("图片上传错误2，请重新上传", U('Ent/index'));exit();
                    }
                    if(!empty($url_img)){
                        $save['img'] = $url_img['activity_img'];
                    }
                   
                    $save['title']          = I('title');
                    $save['introduction']   = I('introduction');
                    $save['details_title']  = I('details');
                    $save['details_content']= I('editor');
                    $save['status']         = I('number');
                    $listsave = M('new_activity')->where('id='.$where)->save($save);
                }
                if($listsave){
                    $this->success("修改成功！", U('Ent/index'));exit();
                }else{
                    $this->success("修改该失败！请重新修改", U('Ent/index'));exit();
                }
            }

            if($type =='type'){//二维码
                if($tt >1){
                    $this->success("图片上传太多，请重新上传", U('Ent/addAdmin'));exit();
                }else{
                    $addcheck['check_url']        = $url_img['photo'];
                    $addcheck['createtime']        = time();
                    $check = M('check')->add($addcheck);
                    if($check){
                        $this->success("图片上传成！", U('Ent/addAdmin'));exit();
                    }else{
                         $this->success("图片上传失败！请重新上传", U('Ent/addAdmin'));exit();
                    }
                }
            }
            if(!empty($count)){////星级宠物
                                   
                if($tt !== 2){
                    $this->success("图片上传错误3，请重新上传", U('Ent/addAdmin'));exit();
                }else{ 
                    $image[] = array('img'=>$url_img[0],'createtime'=>time(),'big_img'=>$url_img[1],'status'=>$count);
                    $listimg = M('list_image')->addAll($image);
                    if($listimg){
                        $this->success("图片上传成功", U('Ent/addAdmin'));exit();
                    }else{
                        $this->success("图片上传失败，请重新上传！", U('Ent/addAdmin'));exit();
                    }
                }
                
            }
            $title      = $_POST['title'];//简介标题
            $introd     = $_POST['introduction'];//简介内容
            $details    = $_POST['details'];//详情标题
            $sum        = $_POST['sum'];//状态
            $editor     = $_POST['editor'];//详情内容
            if(!empty($title) && !empty($introd) && !empty($details) && !empty($sum) && !empty($editor)){
                if($tt > 1){//活动  攻略
                 $this->success("图片上传太多，请重新上传", U('Ent/addAdmin'));exit();
                }
                $addactivity['img']             = $url_img['activity_img'];
                $addactivity['title']           = $title;
                $addactivity['introduction']    = $introd;
                $addactivity['createtime']      = time();
                $addactivity['details_title']   = $details;
                $addactivity['details_content'] = $editor;
                $addactivity['status']          = $sum;
                // /var_dump($addactivity);die;
               
                $add_acticity = M('new_activity')->add($addactivity);
                if($add_acticity){
                    $this->success("数据添加成功！", U('Ent/addAdmin'));exit();
                }else{
                    $this->success("数据添加失败！", U('Ent/addAdmin'));exit();
                }
                
            }
        }
         $this->success("数据错误！请重新提交！", U('Ent/addAdmin'));exit(); 
    }

    /**
     * 首页列表
     * @return [type] $p 页码
     *@return [type] $list 列表信息
     */
    public function index()
    {   
            //设置字符集
            header("Content-Type:text/html; charset=utf-8");
            $Model_list = I('list');
            $key = I('listRows');

            $p = $_GET['p']?$_GET['p']:1;
            if($Model_list=='listimg'){//星级宠物列表
                $model = M('list_image'); 
                $type = 1;

            }elseif($Model_list=='activity'){//活动 | 攻略

                $model = M('new_activity'); 
               
                if($key=='newactivity'){//最新活动
                     $type = 2;
                   
                    $where['status'] = 1;
                }else{//游戏攻略
                     $type = 5;
                    $where['status'] = 2;
                }

            }elseif($Model_list=='newserver'){//新服名称

                $model = M('new_server');
                $type = 3;

            }else{//新闻列表

                $model = M('journalism');
                $type = 4;
            }
            if($Model_list=='rotation'){

                 $model = M('rotation');
                $type = 6;
            }

            if($Model_list=='activity'){

                $list=$model->where($where)->order('createtime desc')->page($p.',15')->select();
                
            }else{

                $list=$model->order('createtime desc')->page($p.',15')->select();
            }
            
            
            $count=$model->where($where)->count()/15;
            $Page=new \Think\Page($count,1);
            $show=$Page->show();
            $this->assign('type',$type);//查询表状态
            $this->assign('list',$list);//列表
            $this->assign('page',$show);
            $this->display();   

    }

    public function del(){//删除
        $list = I('list');// 1 jour 2 list 3 ctivity 4 server
        $where['id'] = I('register');//ID

        if($list=='jour'){
            $model = M('journalism');
        }

        if($list=='list'){
            $model = M('list_image');
        }
        if($list=='ctivity'){
            $model = M('new_activity');
        }
        if($list=='server'){
            $model = M('new_server');
        }
         if($list=='rotation'){
            $model = M('rotation');
        }
        $del  = $model->where($where)->delete();
        if($del){
            $data = array('result' => 1, 'msg' => "数据删除成功！");
            echo json_encode($data);die;
        }else{
            $data = array('result' => 0, 'msg' => "数据删除失败！");
            echo json_encode($data);die;
        }
    }

    public function rotation(){//轮播图
            $list       = I('list');
            $listrow    = I('listRows');

            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     314572800 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Public/upload/'; // 设置附件上传根目录
            $upload->savePath  =     ''; // 设置附件上传（子）目录
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = '@.ORG.Image';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            $upload->replace           = true;
            //删除原图
            $upload->thumbRemoveOrigin  = true;
            // 上传文件
            $info=array();
           
            $info1   =  $upload->upload();
            foreach ($info1 as $key=>$value)
            {

                $imgs=$_SERVER["DOCUMENT_ROOT"].'/hcxy/server/Public/upload/'.$value['savepath'].$value['savename'];
                $imgsname = $value['savename'];

                $path = $this->Test($imgs,$imgsname);
                $addrotation['url_img']     = 'http://image.jswl.cc/'.$path['key'];//七牛云 图片路径

                if(!empty($list) && !empty($listrow)){
                    if($list=='rotation'){
                        $img['id'] = $listrow;
                        $rotation = M('rotation')->where($img)->save($addrotation);

                        if($rotation){
                            $this->success("图片上传成！", U('Ent/index'));exit();
                        }else{
                            $this->success("图片上传失败！请重新上传", U('Ent/index'));exit();
                        }
                    }
                }
                $addrotation['createtime']     = time();
                $rotation = M('rotation')->add($addrotation);
            }
            
            if($rotation){
                $this->success("图片上传成！", U('Ent/addAdmin'));exit();
            }else{
                 $this->success("图片上传失败！请重新上传", U('Ent/addAdmin'));exit();
            }

    }
          
  
  
    /**
     * 修改密码
     * @php $pass $name $new
     */
    public function upd(){ 

        if(IS_POST){
            $model = M('user');
            $pass=$_POST['password'];
            $name['username']=array('username',$_SESSION['username']);
            $new=$_POST['newpassword'];
            if(empty($new) || empty($pass)){
                $this->success('密码不能为空!',U('Ent/upd'),2);
                    exit();
            }
            if($new !== $pass){
                $this->success('密码不一致!',U('Ent/upd'),2);
                    exit();
            
            }
      
            if($model->where($name)->find()){
                $pas=md5($pass);
                $arr=array('password'=>$pas);
                $user = $model->where($name)->save($arr);
                $model->getLastSql();
                if($user){
                     $this->success('密码修改完成!',U('Ent/upd'),2);
                    exit();
                }else{
                     $this->error("密码修改失败!!",U('Ent/upd'));exit();
                }
               
            }else{
                 $this->error("密码修改失败!!",U('Ent/upd'));exit();
            }

        }
        $this->display();
    }


    /**
     *后加Excel 导入数据库
     */
        //导入
    public function eximport(){   
        $upload = new \Think\Upload();
        $upload->maxSize   =     3145728 ;    
        $upload->exts      =     array('xls', 'csv', 'xlsx');  
        $upload->rootPath  =      './Public';    
        $upload->savePath  =      '/excel/';    
        $info   =   $upload->upload();
        if(!$info){
            $this->error($upload->getError());
        }else{
            $filename='./Public/'.$info['excel']['savepath'].$info['excel']['savename'];
            import("Org.Excel.ExcelReader");
            $ExcelReader=new \ExcelReader();
            $arr=$ExcelReader->reader_excel($filename);
            foreach ($arr as $key => $value) {
                $data['gift_token'] = $arr[$key]['0'];//0 1 2 3 4 分别对应 A B C D
                $data['createtime'] = time();
                $add  = M('gift_check')->add($data);  die;    
            } 
            if($add){
                    $this->success('导入成功');
                }else{
                    $this->success('导入失败');
                } 
        }
    }

public function QiniuUp(){

        //var_dump($_FILES['upfile']);die;
        $file = $_FILES['upfile'];
        $accessKey = qingniuAccessKey();
        $secretKey = qingniuSecretKey();
        $bucket    = qingniuspace();
        $auth      = new Auth($accessKey, $secretKey);
        $token     = $auth->uploadToken($bucket);//获取七牛云token
        $filePath  = $file['tmp_name'];//图片本地地址
        $key       = time().$file['name'];//图片名字
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);//发送参数接受返回值

        if ($err !== null) {
            $return['state'] = '上传失败';
             echo json_encode($return);
        } else {//成功返回值
            $return['state'] = "SUCCESS";
            $return['url'] = "http://image.jswl.cc/".$ret['key'];
            $return['title'] = $ret['key'];
            $return['original'] = $ret['key'];
            $return['type'] = substr(strrchr($ret['key'], '.'), 1);
            $return['size'] = $file['size'];
            echo json_encode($return);
        }
   
    }

public function Test($imgs,$imgsname){

        $accessKey=qingniuAccessKey();
        $secretKey=qingniuSecretKey();
        $bucket = qingniuspace();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);//获取七牛云token
        $filePath = $imgs;//图片本地地址
        $key = $imgsname;//图片名字
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);//发送参数接受返回值
        //var_dump($ret, $err);die;
        if ($err !== null) {
             return $err;
        } else {//成功返回值
            return $ret;
        }
   
    }


}
